package com.gzsxy.esjy.service.auth.shiro.realm;

import com.gzsxy.esjy.common.base.exception.impl.CustomAssert;
import com.gzsxy.esjy.common.base.result.ResultCodeEnum;
import com.gzsxy.esjy.service.auth.service.AuthService;
import com.gzsxy.esjy.service.auth.shiro.config.MyAuthenticationToken;
import com.gzsxy.esjy.service.base.dto.response.UserRsp;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import javax.xml.ws.Action;

/**
 * @author xiaolong
 * @version 1.0
 * @description: TODO
 * @date 2022/2/7 15:23
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private AuthService authService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        //强转自定义的token外加dchool字段校验登录
        MyAuthenticationToken authtoken = (MyAuthenticationToken)token;

        //获取用户输入的账号
//        String account = (String) token.getPrincipal();
        UserRsp account1 = authService.getByAccount(authtoken.getUsername(),authtoken.getSchool());
        //用户不存在
        if (ObjectUtils.isEmpty(account1)){
            throw new UnknownAccountException();
            //账号已被锁定，禁止登录
        } else if (account1.getFreeze() !=null && account1.getFreeze()==1){
            // 帐号冻结，非正常
            throw new LockedAccountException();
        }
        //密码认证。shiro做 ,加密了
        // user参数存入subject-返回为授权
        return new SimpleAuthenticationInfo(account1,account1.getPassword(),getName());
    }


    /**
     * @description: 在自定义realm中复写supports方法，使之能识别自定义token
     * @param
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null && token instanceof MyAuthenticationToken;
    }
}
